package com.caiyouxi.goods.service;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.model.CouponType;
import com.caiyouxi.goods.mapper.GoodsCategoryMapper;
import com.caiyouxi.goods.mapper.GoodsInfoMapper;
import com.caiyouxi.goods.mapper.GoodsPropertiesConfigMapper;
import com.caiyouxi.goods.mapper.GoodsVersionMapper;
import com.caiyouxi.goods.model.GoodsCategory;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.goods.model.GoodsPropertiesConfig;
import com.caiyouxi.goods.model.GoodsVersion;
import com.caiyouxi.order.model.OrderBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 商品信息
 * chensong
 */
@Service
public class GoodsInfoService extends BaseService {
    
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    private GoodsVersionMapper goodsVersionMapper;
    @Autowired
    private GoodsPropertiesConfigMapper goodsPropertiesConfigMapper;
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    public GoodsInfo select_goodsInfo_by_id(Long goodsInfoId){
        String key = "GOODS_KEY_GOODS_ID" + goodsInfoId;
        GoodsInfo gInfo = (GoodsInfo) redisService.get(key);
        if(gInfo == null){
            gInfo = goodsInfoMapper.select_goods_info(goodsInfoId);
            redisService.set(key,gInfo);
        }
        return gInfo;
    }

    public void add_goods_info(GoodsInfo goodsInfo){
        //添加商品版本号
        GoodsVersion gv = new GoodsVersion();
        gv.setGoods_id(Integer.valueOf(goodsInfo.getId().toString()));//商品编号
        gv.setData(getJsonByBean(goodsInfo).toJSONString());
        gv.setVersion(1);//版本号
        gv.setRelease_time(new Date());//发布时间
        gv.setUp_to_date(1);//是否是最新版本
        goodsVersionMapper.add_goods_version(gv);
        Log.d("保存版本信息结束");
        goodsInfoMapper.add_goods_info(goodsInfo);
        Log.d("保存商品信息结束");
    }

    /**
     * 更新商品
     */
    @Transactional
    public void update_goods_info(GoodsInfo goodsInfo){

        //每次保存版本加1
        goodsInfo.setVersion(goodsInfo.getVersion()+1);
        goodsInfo.setLast_update_time(new Date());
        goodsInfoMapper.update_goods_info(goodsInfo);

        /**更新版本*/
        GoodsVersion goodsVersion = new GoodsVersion();
        goodsVersion.setGoods_id(new Long(goodsInfo.getId()).intValue());
        goodsVersion.setVersion(goodsInfo.getVersion());
        goodsVersion.setRelease_time(new Date());
        goodsVersion.setIs_deleted(false);
        goodsVersionMapper.add_goods_version(goodsVersion);

    }

    /**
     * 上架
     */
    public ResData update_status (GoodsInfo goodsInfo){
        //上架
        goodsInfoMapper.update_status( goodsInfo);
        //查商品信息
        GoodsInfo newGoodsInfo = goodsInfoMapper.select_goods_info(goodsInfo.getId());
        String  GoodsInfoStr =    JSONObject.toJSON(newGoodsInfo).toString();

        //查商品版本
        GoodsVersion goodsVersion = new GoodsVersion();
        goodsVersion.setGoods_id(new Long(newGoodsInfo.getId()).intValue());
        goodsVersion.setVersion(newGoodsInfo.getVersion());
        GoodsVersion newGoodsVersion  =  goodsVersionMapper.get_goods_version(goodsVersion);
        if(StringUtils.isEmpty(newGoodsVersion)){
            //logger.info("所查询到商品版本为空");
            return failed(ErrorCode.SYS_BUSSINESS_ERROR.getCode(),ErrorCode.SYS_BUSSINESS_ERROR.getMsg()+"_所查询到商品版本为空",null);
        }

        //修改版本
        newGoodsVersion.setData(GoodsInfoStr);
        newGoodsVersion.setRelease_time(new Date());
        goodsVersionMapper.update_goods_version(newGoodsVersion);
        return  success(null);
    }




    public void delete_goods_info(GoodsInfo goodsInfo){
        goodsInfoMapper.delete_goods_info(goodsInfo.getId());
    }
    
    public JSONObject getJsonByBean(GoodsInfo goodsInfo){
        JSONObject json = new JSONObject();
        json.put("id", goodsInfo.getId());
        json.put("title", goodsInfo.getTitle());
        json.put("sub_title", goodsInfo.getSub_title());
        json.put("ad_title", goodsInfo.getAd_title());
        json.put("category_id", goodsInfo.getCategory_id());
        json.put("stock", goodsInfo.getStock());
        json.put("reduce_stock", goodsInfo.getReduce_stock());
        json.put("is_digital_goods", goodsInfo.getIs_digital_goods());
        json.put("version", goodsInfo.getVersion());
        json.put("detail", goodsInfo.getDetail());
        json.put("remark", goodsInfo.getRemark());
        json.put("effective_time", goodsInfo.getEffective_time());
        json.put("expire_time", goodsInfo.getExpire_time());
        json.put("seller_user_id", goodsInfo.getSeller_user_id());
        json.put("status", goodsInfo.getStatus());
        json.put("off_reason", goodsInfo.getOff_reason());
        json.put("is_deleted", goodsInfo.isIs_deleted());
        json.put("is_reserved", goodsInfo.getId());
        json.put("properties", goodsInfo.getIs_reserved());
        json.put("market_price", goodsInfo.getMarket_price());
        json.put("price", goodsInfo.getPrice());
        json.put("currency_code", goodsInfo.getCurrency_code());
        json.put("currency_type", goodsInfo.getCurrency_type());
        json.put("account_code", goodsInfo.getAccount_code());
        json.put("allowed_coupon_types", goodsInfo.getAllowed_coupon_types());
        json.put("create_time", goodsInfo.getCreate_time());
        json.put("last_update_time", goodsInfo.getLast_update_time());
        return json;
    }

    /**
     * 查询有效期内的商品
     * @param goods_id
     * @return
     */
    public GoodsInfo select_goods_info_on_usefull(Integer goods_id){
        HashMap<String, Object> map = new HashMap();
        Date date = new Date();
        map.put("nowDate", date);
        map.put("id", goods_id);
        return goodsInfoMapper.select_goods_info_on_usefull(map);
    }

    /**
     * 商品参数校验
     */
    public boolean check_goods_mess(OrderBean bean){
        //查询有效期内的商品信息
        Log.d("商品Id" + bean.getGoods_id());
        GoodsInfo obs = select_goods_info_on_usefull(bean.getGoods_id());
        if(obs == null || !"ON".equals(obs.getStatus())){
            Log.d("无此商品或商品状态不可用" + obs == null ? "" : obs.getStatus());
            return false;
        }
        Integer category_id = obs.getCategory_id();//商品品类
        HashMap<String, Object> map = new HashMap();
        map.put("category_id",category_id);
        map.put("apply_to","GOODS");//GOODS：新增商品时需要填写该属性；ORDER：下单时需要填写这些属性；DELIVER：发货时需要填写这些属性。
        List<GoodsPropertiesConfig> gpcs = goodsPropertiesConfigMapper.select_goods_properties_config_by_category_id_and_apply_to(map);
        String properties = obs.getProperties();
        if(!StringUtils.isEmpty(properties)){
            JSONObject jsb = JSONObject.parseObject(properties);
            for(GoodsPropertiesConfig gpc : gpcs){
                JSONObject jos = JSONObject.parseObject(gpc.getConfig());
                String keyValue = jsb.getString(gpc.getKey());
                if(!StringUtils.isEmpty(keyValue)){
                    Integer min = jos.getInteger("min");
                    Integer max = jos.getInteger("max");
//                String type = jos.getString("type");
//                String keyValue = null;
//                switch (type){
//                    case "TEXT":
//                        keyValue = jsb.getString(gpc.getKey());
//                }
                    if(min > 0){
                        if(StringUtils.isEmpty(keyValue)){
                            Log.d(gpc.getKey() + "值为空");
                            Log.d("商品校验失败");
                            return false;
                        }
                    }
                    if(max < keyValue.length()){
                        Log.d(gpc.getKey() + "字段值超长");
                        Log.d("字段值超长");
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 根据app_id查询商品
     */
    public GoodsInfo select_goods_info_by_app_id(String app_id){
        String key = "GOODS_INFO_BY_APP_ID" + app_id;
        GoodsInfo gInfo = (GoodsInfo) redisService.get(key);
        if(gInfo == null){
            gInfo = goodsInfoMapper.select_goods_info_by_app_id(app_id); 
        }
        return gInfo;
    }

    /**
     * 校验库存
     */
    public boolean check_goods_num(GoodsInfo gInfo,Integer num){
        if(!"UNLIMITED".equals(gInfo.getReduce_stock())){
            //非无限库存
            Integer stock = gInfo.getStock();//当前库存
            if(num > stock){
//                Log.d("库存不足");
                return false;
            }
        }
        return true;
    }

    /**
     * 校验该券是否被商品及商品品类允许使用
     */
    public boolean check_coupon_goods(CouponType coupon_type, GoodsInfo gInfo){
        if(gInfo.getAllowed_coupon_types() != null){
            String[] goods_alloweds = gInfo.getAllowed_coupon_types().split("|");
            for(String goods_allowed : goods_alloweds){
                if(goods_allowed != null && goods_allowed.equals(coupon_type.getId().toString()) && coupon_type.getCurrency_type().equals(gInfo.getCurrency_code()) && coupon_type.getAccount_code().equals(gInfo.getAccount_code())){
                    //该券被允许使用
                    return true;
                }
            }
            GoodsCategory goods_category = goodsCategoryMapper.select_goods_category(gInfo.getCategory_id());
            if(goods_category != null){
                if(goods_category.getAllowed_coupon_types() != null){
                    String[] goods_category_alloweds = goods_category.getAllowed_coupon_types().split("|");
                    for(String goods_category_allowed : goods_category_alloweds){
                        if(goods_category_allowed != null && goods_category_allowed.equals(coupon_type.getId().toString())
                                && coupon_type.getCurrency_type().equals(gInfo.getCurrency_code()) && coupon_type.getAccount_code().equals(gInfo.getAccount_code())){
                            //该券被允许使用
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 是否需减库存，如果需减库存并做处理
     */
    public GoodsInfo check_stock(Long goods_id,Integer num,String reduce_stock){
        GoodsInfo gInfo = select_goodsInfo_by_id(goods_id);
        if("UNLIMITED".equals(gInfo.getReduce_stock())){
            //无限库存
            Log.e("无限库存");
        }
        if(reduce_stock.equals(gInfo.getReduce_stock())){
            //减库存
            gInfo.setStock(gInfo.getStock() - num);
            update_goods_info(gInfo);
        }
        return gInfo;
    }
}
